package com.hd.crdao.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hd.crdao.MainActivity;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.bean.LoginInfoBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.MobileDesUtils;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

/**
 * @author Administrator
 * @date 2017/5/16 0016
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    EditText et_username;       //用户名
    EditText et_pasword;        //密码
    Button bt_login;            //登录

    public TextView mToRegister;
    public TextView mToForgetPwd;
    private boolean hasLogin;
    ExpandHeadView mLoginHead;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        et_username = (EditText) findViewById(R.id.et_username);
        et_pasword = (EditText) findViewById(R.id.et_pasword);
        bt_login = (Button) findViewById(R.id.bt_login);
        mToRegister = (TextView) findViewById(R.id.register);
        mToForgetPwd = (TextView) findViewById(R.id.loginproblem);
        mLoginHead = (ExpandHeadView) findViewById(R.id.login_head);

        String rLoginName = getIntent().getStringExtra("loginName");
        String rPassword = getIntent().getStringExtra("password");
        if (!TextUtils.isEmpty(rLoginName) && !TextUtils.isEmpty(rPassword)) {
            et_username.setText(rLoginName);
            et_pasword.setText(rPassword);
        }
    }

    @Override
    protected void initListener() {
        bt_login.setOnClickListener(this);
        mToForgetPwd.setOnClickListener(this);
        mToRegister.setOnClickListener(this);

        mLoginHead.getLeftArrowLL().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    protected void initData() {
        mToForgetPwd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//增加下划线
        mToForgetPwd.getPaint().setAntiAlias(true);//抗锯齿
        mToRegister.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//增加下划线
        mToRegister.getPaint().setAntiAlias(true);//抗锯齿
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                login();
                break;
            case R.id.register:
                startActivity(new Intent(UIUtils.getContext(), RegisterActivity.class));
                finish();
                break;
            case R.id.loginproblem:
                startActivity(new Intent(UIUtils.getContext(), ForgetPwdActivity.class));
                finish();
                break;
        }
    }

    /**
     * 登陆按钮
     */
    private void login() {
        String username = et_username.getText().toString().trim();
        String password = et_pasword.getText().toString().trim();
        if (checkUserAndPassWord(username, password)) {
            loginCarBusiness(username, password);
        }
    }

    /**
     * 校验用户名和密码
     *
     * @param username
     * @param password
     * @return
     */
    private boolean checkUserAndPassWord(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            MyToast.show("请输入登录名");
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            MyToast.show("请输入密码");
            return false;
        }
        return true;
    }

    /**
     * 检查车商登录的操作
     *
     * @param username
     * @param password
     */
    public void loginCarBusiness(String username, String password) {

        String EncPassword = MobileDesUtils.strEnc(password, Constants.FIRSTKEY, null, null);
        String data = username + "~" + EncPassword;
        OkHttpUtils.post().url(Constants.LOGINURL)
                .addParams("data", data)
                .addParams("sign", Constants.SIGN)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show("服务器连接错误或异常");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        LoginInfoBean loginInfoBean = new Gson().fromJson(response, LoginInfoBean.class);
                        if (loginInfoBean.getSuccess() == 0) {
                            SPUtils.clear();
                            hasLogin = true;
                            //获取别名
                            if (loginInfoBean.getUsertype() == Config.CARBUSINESS_ACCOUNT) {    //车商
                                SPUtils.saveInt(Config.userType, Config.CARBUSINESS_ACCOUNT);
                                JPushInterface.setAlias(LoginActivity.this,
                                        loginInfoBean.getData().getUser().getId(), null);

                                SPUtils.saveString(Config.userId, loginInfoBean.getData().getUser().getId());
                                SPUtils.saveString(Config.businessId, loginInfoBean.getData().getId());
                                SPUtils.saveString(Config.recomMobile, loginInfoBean.getData().getRecomMobile());
                                MyToast.show(loginInfoBean.getMessage());
                                toMainActivity();
                                finish();
                            } else if (loginInfoBean.getUsertype() == Config.CHILD_ACCOUNT) { //子账户
                                SPUtils.saveString(Config.childUser, response);
                                SPUtils.saveInt(Config.userType, Config.CHILD_ACCOUNT);
                                JPushInterface.setAlias(LoginActivity.this,
                                        loginInfoBean.getCarBusiness().getUser().getId(), null);
                                startActivity(new Intent(UIUtils.getContext(), ChildUserActivity.class));
                                finish();
                            }
                        } else {
                            MyToast.show(loginInfoBean.getMessage());
                        }
                    }
                });
    }


    @Override
    public void onBackPressed() {
        SPUtils.saveString("check", "home");
        finish();
    }

    private void toMainActivity() {
        Intent intent = new Intent(UIUtils.getContext(), MainActivity.class);
        SPUtils.saveBoolean("hasLogin", hasLogin);
        SPUtils.saveString("check", "home");
        startActivity(intent);
    }

}
